package com.javaear.zblog4java.system.plugin.mybatisplus;

import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author aooer
 */
@Component
public class TableNameAnnotationProcessor implements BeanPostProcessor {

    private static final Class<?> GeneralClass = GeneralMapper.class;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        try {
            if (bean instanceof MybatisSqlSessionFactoryBean) {
                Configuration configuration = ((MybatisSqlSessionFactoryBean) bean).getObject().getConfiguration();
                configuration.getTypeAliasRegistry().getTypeAliases().entrySet().stream().forEach(type -> {
                    TableName tableName = type.getValue().getAnnotation(TableName.class);
                    if (tableName != null) {
                        String packageName = type.getValue().getPackage().getName();
                        MapperBuilderAssistant assistant = new MapperBuilderAssistant(configuration, packageName);
                        assistant.setCurrentNamespace(GeneralClass.getName().concat(".").concat(type.getValue().getSimpleName()));
                        new GeneralSqlInjector().inject(configuration, assistant, GeneralClass, type.getValue(), null);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

}
